package com.hjy.core.transport.socket.client;


import com.hjy.common.entity.RpcRequest;
import com.hjy.core.nacos.NacosServiceRegistry;
import com.hjy.core.nacos.ServiceRegistry;
import com.hjy.core.provider.DefaultServiceProvider;
import com.hjy.core.provider.ServiceProvider;
import com.hjy.core.transport.RpcClient;
import lombok.AllArgsConstructor;
import lombok.Data;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;

/**
 * 客户端类通用接口
 *
 * @author ziyang
 */
@Data

public class SocketClient implements RpcClient {

    private ServiceRegistry serviceRegistry;

    public SocketClient() {
        serviceRegistry = new NacosServiceRegistry();
    }

    @Override
    public Object sendRequest(RpcRequest rpcRequest) {
        InetSocketAddress inetSocketAddress = serviceRegistry.lookupService(rpcRequest.getInterfaceName());
        try (Socket socket = new Socket(inetSocketAddress.getHostName(),inetSocketAddress.getPort())) {
            // 将请求发送出去
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
            ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());
            objectOutputStream.writeObject(rpcRequest);
            objectOutputStream.flush();
            return objectInputStream.readObject();
        } catch (IOException | ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }
}
